# coding = utf-8

'''
生成GLCM的数据
'''

import cv2,os
import numpy as np
import matplotlib.pyplot as plt
import SimpleITK as sitk
from PIL import Image
import math
from tqdm import tqdm

def glgc(image, a, b, instace_level=32):
    glgc_matrix = np.zeros((instace_level, instace_level))

    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            f1 = image[i][j]
            if i+a < 0 or i+a >= image.shape[0] or j + b < 0  or j + b >= image.shape[1]:
                continue
            else:
                f2 = image[i+a][j+b]
            glgc_matrix[f1][f2] += 1

    return glgc_matrix


def get_glgc_map(image, kernel, instance_level=32, a=0, b=1):
    entropy_map = np.zeros((image.shape[0], image.shape[1]))
    energy_map = np.zeros((image.shape[0], image.shape[1]))
    contrast_map = np.zeros((image.shape[0],image.shape[1]))
    differ_moment = np.zeros((image.shape[0], image.shape[1]))

    supply_matrix = np.zeros((instance_level, instance_level))
    for i in range(supply_matrix.shape[0]):
        for j in range(supply_matrix.shape[1]):
            supply_matrix[i][j] = math.pow((i-j), 2)

    for i in range(0+kernel//2, image.shape[0]-kernel//2):
        for j in range(0+kernel//2, image.shape[1]-kernel//2):
            matrix1 = glgc(image[i - kernel // 2: i + kernel // 2 + 1, j - kernel // 2: j + kernel // 2 + 1], a=a, b=b,
                           instace_level=instance_level)
            matrix = matrix1 / matrix1.sum()


            entropy_map[i,j] = (-matrix * np.log(matrix+0.0000001)).sum()
            energy_map[i,j] = np.power(matrix, 2).sum()
            contrast_map[i,j] = (supply_matrix*matrix).sum()
            differ_moment[i, j] = ((1/(1+supply_matrix)) * matrix).sum()


    return (entropy_map, energy_map, contrast_map, differ_moment)


def main():
    path = "/datasets/DongbeiDaxue/chengkun_only_liver"
    for case_id in range(70):
        case_id = "case_{}".format(str(case_id).zfill(5))
        case_path = os.path.join(path, case_id)
        imging = os.path.join(case_path, "imaging")
        with tqdm(total=len(os.listdir(imging)) - 1, ascii=True, desc='generate', dynamic_ncols=True) as pbar:
            for item in sorted(os.listdir(imging)):
                file_name = os.path.join(imging, item)
                image = np.load(file_name)
                image = image * 255
                image = image.astype(np.int64)
                image = image/8
                image = image.astype(np.uint8)

                get_glgc_map(image=image, kernel=5, instance_level=32, a=1, b=1)

                pbar.update(1)






if __name__ == '__main__':
    main()
